<template>
  <i>还剩：{{ timeStr }}</i>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { formatTime } from "../util/tools";
export default {
  data() {
    return {
      timeStr: "00:00",
      timer: null,
    };
  },
  mounted() {
    // console.log(this.item);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    ...mapActions("detail", ["saveStudy"]),
    runTimer(minutes) {
      let seconds = minutes;
      // let seconds = minutes * 60;
      this.timer = setInterval(async () => {
        if (seconds <= 0) {
          this.timeStr = "00:00";
          clearInterval(this.timer);
          await this.saveStudy(this.item.id);
          alert("标记为已读！");
        } else {
          this.timeStr = formatTime(--seconds);
        }
      }, 1000);
    },
  },
  computed: {
    ...mapState("detail", ["item"]),
  },
  watch: {
    item(n, o) {
      if (n.time) {
        this.runTimer(n.time);
      }
    },
  },
};
</script>

<style>
</style>